package com.components.headerrecycler

import android.content.Context
import android.content.SharedPreferences
import android.content.res.TypedArray
import android.text.TextUtils
import android.util.AttributeSet
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.airbnb.lottie.LottieAnimationView
import com.bumptech.glide.Glide
import com.components.headerrecycler.R
import com.scwang.smart.drawable.ProgressDrawable
import com.scwang.smart.refresh.classics.ArrowDrawable
import com.scwang.smart.refresh.layout.api.RefreshHeader
import com.scwang.smart.refresh.layout.api.RefreshKernel
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.constant.RefreshState
import com.scwang.smart.refresh.layout.constant.SpinnerStyle
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.*

/**
 * @Author LuoKun
 * @Des 自定义刷新Header
 */
class CustomClassicsHeader : LinearLayout, RefreshHeader {

    private var key_last_update_time: String = "LAST_UPDATE_TIME"

    /**上次更新 M-d HH:mm*/
    private var refresh_header_update: String = ""

    /**上次更新 M-d HH:mm*/
    private var mTextUpdate: String = ""
    private var mLastUpdateFormat: DateFormat
    private var mLastTime: Date? = null
    private var mShared: SharedPreferences
    private var mEnableLastTime: Boolean = true

    private var mTopImage: LottieAnimationView
    private var mArrowView: ImageView
    private var mProgressView: ImageView
    private var mHeaderText: TextView
    private var mLastUpdateText: TextView
    private var mProgressDrawable: ProgressDrawable

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        View.inflate(context, R.layout.layout_custom_classics_header, this)
        mTopImage = this.findViewById(R.id.imageTop)
        mArrowView = this.findViewById(R.id.imageAnim)
        mProgressView = this.findViewById(R.id.imageAnim2)
        mHeaderText = this.findViewById(R.id.tvToast)
        mLastUpdateText = this.findViewById(R.id.tvRefreshTime)
        mProgressDrawable = ProgressDrawable()
        mProgressView.setImageDrawable(mProgressDrawable)
        mArrowView.setImageDrawable(ArrowDrawable())

        //设置刷新头部图片
        if (!TextUtils.isEmpty(ConstantManage.REFRESH_TOP_IMG)) {
            Glide.with(context).load(ConstantManage.REFRESH_TOP_IMG).into(mTopImage)
        }

        var typedArray: TypedArray =
            context.obtainStyledAttributes(attrs, R.styleable.ClassicsHeader)
        mTextUpdate = if (typedArray.hasValue(R.styleable.ClassicsHeader_srlTextUpdate)) {
            typedArray.getString(R.styleable.ClassicsHeader_srlTextUpdate).toString()
        } else if (!TextUtils.isEmpty(refresh_header_update)) {
            refresh_header_update
        } else {
            context.getString(R.string.refresh_header_update)
        }
        mLastUpdateFormat = SimpleDateFormat(mTextUpdate, Locale.getDefault())
        key_last_update_time += context.javaClass.name
        mShared = context.getSharedPreferences("ClassicsHeader", Context.MODE_PRIVATE)
        setLastUpdateTime(Date(mShared.getLong(key_last_update_time, System.currentTimeMillis())))
    }

    override fun getView(): View {
        //返回自己即可,即当前视图本身,不能null
        return this
    }

    override fun getSpinnerStyle(): SpinnerStyle {
        //指定为平移,不能null
        return SpinnerStyle.Translate
    }

    override fun onStartAnimator(refreshLayout: RefreshLayout, height: Int, maxDragHeight: Int) {
        mProgressDrawable.start()
    }

    override fun onFinish(refreshLayout: RefreshLayout, success: Boolean): Int {
        mProgressDrawable.stop()
        mProgressView.visibility = View.GONE
        mArrowView.visibility = View.GONE
        if (success) {
            mHeaderText.setText(R.string.refresh_header_complete)
            mLastTime?.apply {
                setLastUpdateTime(Date())
            }
        } else {
            mHeaderText.setText(R.string.refresh_header_fail)
        }
        //延迟600毫秒之后再弹回
        return 600
    }

    override fun onStateChanged(
        refreshLayout: RefreshLayout,
        oldState: RefreshState,
        newState: RefreshState
    ) {
        val updateView: View = mLastUpdateText
        when (newState) {
            RefreshState.None -> {
                updateView.visibility = if (mEnableLastTime) {
                    VISIBLE
                } else {
                    GONE
                }
            }
            RefreshState.PullDownToRefresh -> {
                mHeaderText.setText(R.string.refresh_header_start_refresh)
                mArrowView.visibility = View.VISIBLE
                mProgressView.visibility = View.INVISIBLE
                mArrowView.animate().rotation(0F)
            }
            RefreshState.Refreshing -> {
                mHeaderText.setText(R.string.refresh_header_refreshing)
                mProgressView.visibility = View.VISIBLE
                mArrowView.visibility = View.INVISIBLE
            }
            RefreshState.ReleaseToRefresh -> {
                mHeaderText.setText(R.string.refresh_header_release_refreshing)
                mArrowView.animate().rotation(180F)
            }
            RefreshState.Loading -> {
                updateView.visibility = if (mEnableLastTime) {
                    INVISIBLE
                } else {
                    GONE
                }
            }
        }
    }

    override fun setPrimaryColors(vararg colors: Int) {

    }

    override fun onInitialized(kernel: RefreshKernel, height: Int, maxDragHeight: Int) {

    }

    override fun onMoving(
        isDragging: Boolean,
        percent: Float,
        offset: Int,
        height: Int,
        maxDragHeight: Int
    ) {

    }

    override fun onReleased(refreshLayout: RefreshLayout, height: Int, maxDragHeight: Int) {

    }

    override fun onHorizontalDrag(percentX: Float, offsetX: Int, offsetMax: Int) {

    }

    override fun isSupportHorizontalDrag(): Boolean {
        return false
    }

    private fun setLastUpdateTime(time: Date): CustomClassicsHeader {
        val thisView = this
        mLastTime = time
        mLastUpdateText.text = mLastUpdateFormat.format(time)
        if (mShared != null && !thisView.isInEditMode) {
            mShared.edit().putLong(key_last_update_time, time.time).apply()
        }
        return this
    }

}